package com.denghq.projectbuilder.component.syslog.thread;

import com.denghq.projectbuilder.component.remote.model.SysLogModel;
import com.denghq.projectbuilder.component.remote.service.OprLogService;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
public class SysLogInsertExec implements Runnable {


    private final OprLogService oprLogService;

    private final int BATCH_INSERT_NUM = 50;//批量写入条数
    private final int MAX_WAIT_TIME = 10;//最大等待时间，单位：秒

    public SysLogInsertExec(OprLogService oprLogService) {
        this.oprLogService = oprLogService;
    }

    @Override
    public void run() {
        while (true) {
            SysLogHolder holder = SysLogHolder.getInstance();
            List<SysLogModel> sysLogEntityList = new ArrayList<>();
            int num = 0;
            long start = System.currentTimeMillis();
            while (num < BATCH_INSERT_NUM) {
                SysLogModel obj = holder.getOne();
                if (obj != null) {
                    sysLogEntityList.add(obj);
                    num++;
                } else {
                    long end = System.currentTimeMillis();
                    long time = (end - start) / 1000;
                    if (time > MAX_WAIT_TIME && num > 0) {// 相隔大于10秒
                        break;
                    }
                    try {
                        TimeUnit.MILLISECONDS.sleep(200L);
                    } catch (InterruptedException e) {
                        log.info("线程被打断，msg:{}", e.getMessage());
                    }

                }
            }

            realAction(sysLogEntityList);
        }
    }

    private void realAction(List<SysLogModel> sysLogEntityList) {
        try {
            oprLogService.batchSave(sysLogEntityList);
        } catch (Exception e) {
            log.error("批量入库出错，msg：{}", e.getMessage());
        }

    }
}
